<template>
  <div class="content p-t-20" ref="contents" id="contents">
    <el-form :model="qustionForm">
      <div class="row-between">
        <div class="m-b-25 m-r-30 request normal">问卷标题</div>
        <div class="width-90 p-r-50">
          <el-form-item size="medium">
            <el-input v-model="qustionForm.title" placeholder="请输入问卷标题"></el-input>
          </el-form-item>
        </div>
      </div>

      <div class="row-between">
        <div class="m-b-25 m-r-30  bold normal" style="font-size: 19px;">问卷说明</div>
        <div class="width-90 p-r-50">
          <el-form-item>
            <el-input v-model="qustionForm.content" :min-height="192" placeholder="请填写提示"></el-input>
          </el-form-item>
        </div>
      </div>

      <div class="row-between" id="no_center">
        <div class="m-b-25 m-r-30 m-t-40 request normal">问卷题目</div>
        <div class="width-90 p-r-50">
          <el-form-item class="m-t-30" prop="title">
            <!-- 题目开始 -->
            <section class="border flex-col project">
              <div class="row-between p-l-10 p-r-20 m-t-20 m-l-20">
                <div class="flex">
                  <div class="border p-l-20 p-r-20 p-t-10 p-b-10 xxl normal addBtn" style="flex-shrink: 0"
                    @click="pushProject">
                    添加题目</div>
                  <div class="border m-l-20 p-l-20 p-r-20 p-t-10 p-b-10 xxl normal submitBtn" @click="submit">
                    完成问卷
                  </div>
                  <div class="border m-l-20 p-l-20 p-r-20 p-t-10 p-b-10 xxl normal viewBtn" @click="viewTest">
                    预览问卷
                  </div>
                </div>
                <article>
                  <p>评价按5级量表（1-5分）。非常不满意（1分)、不满意(2分)、一般(3分)、满意(4分)、非常满意(5分)</p>
                  <p>1、如果设置了分值，会参与计算。</p>
                  <p>2、可以设置某问题的选项为：没参与/没检查/不了解等，可以写分值0，分值0不参与计算</p>
                </article>
                <span class="border p-l-10 p-r-10 normal plus-project" @click="pushProject"><i class="el-icon-plus"></i>
                </span>
              </div>
            </section>
            <section class="m-t-20 border flex-col project" v-for="(value, j) in section" :key="value.project.id">
              <div class="m-t-20 flex-col m-l-20">
                <div class="row-end m-b-20 p-r-20 p-l-5">
                  <div class="flex-1 normal xl">第{{ j + 1 }}题</div>
                  <div class="normal xl p-r-20 bold">删除题目</div>
                  <div class="border p-l-10 p-r-10 normal minus" @click="deleteProject(value.project.id)">
                    <i class="el-icon-minus" style=""></i>
                  </div>
                </div>
                <div class="p-b-15 p-r-20">
                  <el-input v-model="value.project.title" type="textarea" placeholder="请输入标题"></el-input>
                </div>
                <div class="p-b-15 p-r-20">
                  <el-input v-model="value.project.describe" type="textarea" placeholder="请输入填写提示"></el-input>
                </div>
                <div class="row-between p-b-20">
                  <div>
                    <el-select v-model="value.project.multipleValue" placeholder="请选择"
                      @change="multipleChange(value.project.id)">
                      <el-option v-for="item in multiple" :key="item.value" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                  <div>
                    <el-checkbox v-model="value.project.isRequired">是否必答</el-checkbox>
                  </div>
                  <div>
                    <el-input v-model="value.project.sort" placeholder="排序"></el-input>
                  </div>
                  <div>
                    <el-input v-model="value.project.keyWord" placeholder="关键字，2-6字" maxlength="6"></el-input>
                  </div>
                  <div>
                    <el-select v-model="value.project.sectorValue" placeholder="选择环节">
                      <el-option v-for="item in sector" :key="item.value" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                  <div class="flex-row  p-r-20">
                    <span class="normal xl p-r-20 bold">添加选项</span>
                    <div class="p-l-10 p-r-10 border plus  text-center" @click="addAnswer(value.project.id, 'add')">
                      <i class="el-icon-plus"></i>
                    </div>
                  </div>
                </div>
                <!-- 多选选项 -->
                <TransitionGroup name="fade">
                  <div class="row-between p-r-20 col-center p-b-15 p-t-30" v-for="(v, k) in value.project.options"
                    :key="k">
                    <el-input type="textarea" :placeholder="'请输入答案' + (k + 1)" v-model="v.answer"
                      class="width-60"></el-input>
                    <div class="flex scores">
                      <div class="normal">分数</div>
                      <div class="p-l-10">
                        <el-input-number v-model="v.scores" :step="1" :min="0" :max="5"></el-input-number>
                      </div>
                    </div>
                    <div class="p-l-10 p-r-10 border minus" @click="addAnswer(value.project.id, 'minus', k)">
                      <i class="el-icon-minus"></i>
                    </div>
                    <div class="flex">
                      <div class="p-l-10 p-r-10 border up" @click="moveOption(v, k, 'up')">
                        <i class="el-icon-top"></i>
                      </div>
                      <div class="p-l-10 p-r-10 border down m-l-10" @click="moveOption(v, k, 'down')">
                        <i class="el-icon-bottom"></i>
                      </div>
                    </div>
                  </div>
                </TransitionGroup>
                <!-- 多选选项结束 -->
              </div>
            </section>
            <!-- 题目结束 -->
          </el-form-item>
        </div>
      </div>

      <!-- <el-form-item>
        <div class="width-90 text-center">
          <el-button type="success" @click="submit">提交</el-button>
        </div>
      </el-form-item> -->
    </el-form>
  </div>
</template>

<script>
import { linkDic, addModal } from '@/api/hcem/title'
import { listTypeNew } from "@/api/hcem/type";
export default {
  name: 'wenjuanTpl',
  data() {
    return {
      qustionForm: {
        title: "",
        content: "",
      },
      multiple: [
        {
          value: '3',
          label: '多选'
        },
        {
          value: '1',
          label: '单选'
        },
        {
          value: '2',
          label: '单行文本'
        },
        {
          value: '4',
          label: '多行文本'
        },
      ],
      sector: [],
      section: [
        // {
        //   project: {
        //     id: 0,
        //     title: "", //标题
        //     describe:'',//描述
        //     options: [
        //       //答案
        //       {
        //         id: null,
        //         answer: "", //答案
        //         scores: 3, //得分
        //       },
        //     ],
        //   },
        // },
      ],
      currentTitle: null, //提示
      // multipleValue: '',
      // sectorValue: '',
      // isRequired: false,
      // sort: 0,
      // keyWord: ''
    };
  },
  async mounted() {
    let id = {
      hospCode: this.$route.query.hosp
    }
    if (id !== undefined) {
      let ress = await listTypeNew(id)  //环节列表
      ress.data.map(v => {
        this.sector.push({
          'value': v.id,
          'label': v.link_type_name
        })
      })
      //  console.log(ress,123);
    }
    // let res = await linkDic()  //环节列表
    // if (res.data.length > 0) {
    //   res.data.map(v => {
    //     this.sector.push({
    //       'value': v.dictValue,
    //       'label': v.dictLabel
    //     })
    //   })
    // }

    // console.log(this.$route.query.hosp);
    this.pushProject();
  },
  methods: {
    viewTest() {
      this.submitNoGo()
      // console.log(this.$store.state.hcem);
    },
    pushProject() {
      //增加题目
      let idNumber = this.randomId();
      this.section.push({
        project: {
          id: idNumber,
          title: "", //标题
          describe: '',//描述
          multipleValue: '1',//单选多选值
          sectorValue: '', //环节
          isRequired: true,//是否必填
          sort: this.section.length + 1,    //优先级
          keyWord: '', //关键词
          options: [
            //答案
            {
              pid: idNumber,
              answer: "", //答案
              scores: 0, //得分
              flag: false
            },
            {
              pid: idNumber,
              answer: "", //答案
              scores: 0, //得分
              flag: false
            },
            {
              pid: idNumber,
              answer: "", //答案
              scores: 0, //得分
              flag: false
            },
          ],
        },
      });
      let h = this.$refs.contents.offsetHeight;
      let h2 = this.$refs.contents.scrollHeight + 920;
      this.$nextTick(() => {
        document.documentElement.scrollTop = h2;
      });
      // console.log(h2);
    },
    deleteProject(id) {
      this.$confirm("此操作将永久删除该题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false,
      }).then(() => {
        this.section.find((v, k) => {
          if (v.project.id == id) {
            this.section.splice(k, 1);
          }
        });
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
    addAnswer(pid, action, key) {
      if (action === "add") {
        this.section.find((v, k) => {
          // console.log(123, v);
          if (v.project.id == pid && ![2, 4].includes(Number(v.project.multipleValue))) {
            v.project.options.push({
              pid: pid,
              answer: "", //答案
              scores: 0, //得分
              flag: false
            });
          } else {
            if (v.project.id == pid) this.$message.warning("文本类型不能添加选项");
          }
        });
      }

      if (action === "minus") {
        this.$confirm("此操作将永久删除该选项, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          lockScroll: false,
        }).then(() => {
          this.section.find((v) => {
            if (v.project.id == pid) {
              if (v.project.options.length == 1 && ![2, 4].includes(Number(v.project.multipleValue))) {
                this.$message.warning("最少有一个选项");
                return;
              } else {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              }
              v.project.options.splice(key, 1);
            }
          });
        });
      }
    },
    multipleChange(id) {
      let data = [{
        pid: id,
        answer: "", //答案
        scores: 0, //得分
        flag: false
      },
      {
        pid: id,
        answer: "", //答案
        scores: 0, //得分
        flag: false
      },
      {
        pid: id,
        answer: "", //答案
        scores: 0, //得分
        flag: false
      }]
      this.section.find(v => {
        if ([2, 4].includes(Number(v.project.multipleValue)) && v.project.id == id) {
          v.project.options = []
          return v
        } else {
          if (v.project.options.length == 0 && v.project.id == id) {
            v.project.options.push(...data)
          }
          // v.project.options.push(...data)
        }
        //v.project.id ,
        //  console.log( [2,4].includes(Number(v.project.multipleValue)));
      })

    },
    isPass() {
      //验证
      let t = this.qustionForm;
      let s = this.section;
      let temp = []; //为空就是验证通过
      let tempNum = null;
      //标题不能为空
      if (t.title.length < 2 || t.title == '') {
        this.$message.warning('问卷标题最少两个字')
        return false
      }
      //题目标题不能为空
      let type = s.map((v, k) => {
        if (v.project.title.length < 2 || v.project.title == "") {
          this.$message.warning(`第${k + 1}题标题最少两个字`);
          return false
        }
        if (v.project.keyWord.length < 1 || v.project.keyWord == "") {
          this.$message.warning(`第${k + 1}题关键字不能为空`);
          return false
        }

        if (v.project.multipleValue.length == 0) {
          this.$message.warning(`第${k + 1}题，请选择题目类型`);
          return false
        }
        // if (v.project.sectorValue.length == 0) {
        //   this.$message.warning(`第${k + 1}题，请选择环节`);
        //   return false
        // }
        return true
      });
      if (!type[0]) return false
      //答案不能为空
      s.find((v, k) => {
        let option = v.project.options;
        let find = option.find((value, key) => {
          if (value.answer.length < 1) {
            tempNum = k + 1;
            temp.push(value);
          }
        });
      });

      if (temp.length > 0) {
        this.$message.warning(`第${tempNum}题答案最少一个字符`);
        return false
      }
      if (this.$route.query.hosp == undefined) { //没有医院id传参不能提交
        this.$message.warning(`请选择医院`);
        setTimeout(() => {
          this.$router.push({ path: '/hcem/title' })
        }, 3000);
        return false
      }
      return true
    },
    async submit() {
      // let confirm = this.$confirm("问卷发布后，不能编辑，确认发布吗？", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      //   lockScroll: false,
      // }).then(() => {
      //   return true
      //   // console.log(params);
      // }, () => {
      //  return false
      // });
      // if(!await confirm) return
      // console.log(await confirm);


      if (this.isPass()) {  //是否验证通过
        //this.$message.success("通过验证");
        const SumitData = {
          'title': this.qustionForm.title,
          'description': this.qustionForm.content,
          'hosp': this.$route.query.hosp,
          'hcemTemplatTopic': [
          ],
        }
        this.section.map(v => {
          // console.log(v.keyWord);
          SumitData.hcemTemplatTopic.push({
            'topicName': v.project.title,
            'scoreInfoList': v.project.options.map(value => {
              return {
                'name': value.answer,
                'score': value.scores,
                'flag': false
              }
            }),
            'sort': v.project.sort,
            'linkType': v.project.sectorValue,
            'isRequired': v.project.isRequired ? 1 : 2,
            'tip': v.project.describe,
            'topicType': v.project.multipleValue,
            'keyWord': v.project.keyWord, //关键词
          })
        })
        // console.log(SumitData);
        // return
        let res = await addModal(SumitData)
        this.$router.push({ path: '/hcem/title' })
        if (res.code == 200) {
          this.$message.success("添加成功");
        }
      }
    },
    async submitNoGo() {
      if (this.isPass()) {  //是否验证通过
        //this.$message.success("通过验证");

        const SumitData = {
          'title': this.qustionForm.title,
          'description': this.qustionForm.content,
          'hosp': this.$route.query.hosp,
          'hcemTemplatTopic': [
          ],
        }

        this.section.map(v => {
          // console.log(v.keyWord);
          SumitData.hcemTemplatTopic.push({
            'topicName': v.project.title,
            'scoreInfoList': v.project.options.map(value => {
              return {
                'name': value.answer,
                'score': value.scores,
                'flag': false
              }
            }),
            'sort': v.project.sort,
            'linkType': v.project.sectorValue,
            'isRequired': v.project.isRequired ? 1 : 2,
            'tip': v.project.describe,
            'topicType': v.project.multipleValue,
            'keyWord': v.project.keyWord, //关键词
          })
        })

        this.$store.state.hcem.section = this.section
        this.$store.state.hcem.qustionForm.title = this.qustionForm.title
        this.$store.state.hcem.qustionForm.content = this.qustionForm.content
        this.$router.push({ name: 'viewwenjuan' });
        // console.log(SumitData);
        // return

        // let res = await addModal(SumitData)
        // if(res.code == 200){
        //   this.$message.success("添加成功");
        // }
      }
    },
    randomId() {
      //随机id
      const time = new Date().getTime().toString();
      const timeArr = time.split("");
      const arr = "abcdefghijklmnopqrstuvwxyz".split("");
      timeArr.forEach((item, index) => {
        const random = arr[Math.floor(Math.random() * arr.length)];
        timeArr.splice(index * 2, 0, random);
      });
      return timeArr.join("");
    },
    moveOption(value, num, action) {
      if (num == 0 && action == 'up') return  //到顶了直接返回
      let arr = this.section.find((v) => {  //当前选中的题目
        // console.log(v);
        if (v.project.id == value.pid) return v
      })
      let currentIndex = this.section.findIndex((v) => {  //当前选中的题目的索引，上面可以写成一个懒的写了
        if (v.project.id == value.pid) return v
      })
      if (action == 'down' && num >= arr.project.options.length - 1) return //到底了
      this.currentTitle = num
      if (action == 'up') {
        //不管是UP还是down，等于他们位置互换了
        let temp = this.section[currentIndex].project.options[num - 1] //移动到的位置的值
        this.section[currentIndex].project.options.splice(num, 1, temp)  //交互数组位置，用splice会触发vue更新
        this.section[currentIndex].project.options.splice(num - 1, 1, value)
      } else {
        let temp = this.section[currentIndex].project.options[num + 1] //移动到的位置的值
        this.section[currentIndex].project.options.splice(num, 1, temp)  //交互数组位置，用splice会触发vue更新
        this.section[currentIndex].project.options.splice(num + 1, 1, value)
        //不管是UP还是down，等于他们位置互换了
      }
      //console.log(arr, currentIndex);
      //console.log(this.section)
      //console.log(value,num,action);
    }
  },

};
</script>

<style lang="scss" scoped>
.content {
  padding-left: 30px;
  padding-bottom: 30px;

  .project:nth-child(1) {
    background-color: #fff;
    top: 0;
    position: sticky;
    z-index: 3;
  }

  .project {
    background-color: #fff;

    .plus_hover {
      line-height: 25px;
      width: 30px;
      text-align: center;
    }

    .scores {
      min-width: 240px;
    }
  }
}

//  :hover,:active{
//  border-color: #53A8FF;
// }
.minus {
  // width:36px;
  // height: 38px;
  background-color: rgb(245, 108, 108);
  color: #fff;
  border-color: rgb(245, 108, 108) !important;
  cursor: pointer;

  &:active {
    background-color: rgb(253, 226, 226);
  }

  &:hover {
    background-color: rgb(245, 108, 108, 0.8);
  }
}

.up {
  // width:36px;
  // height: 38px;
  background-color: rgb(103, 194, 58);
  color: #fff;
  border-color: rgb(103, 194, 58) !important;
  cursor: pointer;

  &:active {
    background-color: rgb(156, 195, 70);
  }

  &:hover {
    background-color: rgb(103, 194, 58), 0.8;
  }
}

.down {
  // width:36px;
  // height: 38px;
  background-color: rgb(230, 162, 60);
  color: #fff;
  border-color: rgb(230, 162, 60) !important;
  cursor: pointer;

  &:active {
    background-color: rgb(245, 200, 90);
  }

  &:hover {
    background-color: rgb(230, 162, 60), 0.8;
  }
}

.fade-enter {
  opacity: 0;
}

.fade-enter-active {
  transition: opacity 1s ease-in-out;
}

.fade-leave {
  position: absolute;
}

.fade-leave-active {
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.move {
  transition: transform 1s;
}

.plus {
  background-color: rgb(83, 168, 255);
  color: #fff;
  border-color: rgb(83, 168, 255) !important;
  cursor: pointer;

  &:active {
    background-color: rgb(217, 236, 255);
  }

  &:hover {
    background-color: rgb(102, 177, 255);
  }
}

.plus-project {
  background-color: rgb(22, 94, 131);
  color: #fff;
  border-color: rgb(22, 94, 131) !important;
  cursor: pointer;

  &:active {
    background-color: rgb(217, 236, 255);
  }

  &:hover {
    background-color: rgb(22, 120, 180);
  }
}

.request {
  font-size: 19px;
  font-weight: bold;

  &::after {
    margin-left: 5px;
    content: "*";
    color: red;
  }
}

#no_center {
  align-items: start !important;
}
</style>
<style lang="scss">
//解决postion：sticky失效问题，重写了app-main
.app-main {
  overflow: inherit !important;
}

.submitBtn {
  font-weight: 700;
  cursor: pointer;
  background-color: #67C23A;
  color: white;
  border-color: #67C23A;
}

.viewBtn {
  background-color: #909399;
  color: white;
  border-color: #909399;
  font-weight: 700;
  cursor: pointer;
}

.addBtn {
  background-color: #E6A23C;
  color: white;
  border-color: #E6A23C;
  font-weight: 700;
  cursor: pointer;
}
</style>